﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Controls;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Phone.Info;
using AppsListControl.Shared;
using System.Threading;
using Coding4Fun.AppsListControl.Resources;
using System.Windows.Media;
using System.Collections.Specialized;
using System.Windows.Input;

namespace Coding4Fun.AppsListControl
{
    [TemplateVisualState(Name = StateNormal, GroupName = GroupCommon)]
    [TemplateVisualState(Name = StateLoading, GroupName = GroupCommon)]
    [TemplateVisualState(Name = StateError, GroupName = GroupCommon)]
    public class PublisherAppsControl : Control
    {
        internal const string GroupCommon = "Common";

        internal const string StateNormal = "Normal";
        internal const string StateLoading = "Loading";
        internal const string StateError = "Error";

        private ListBox AppsList;

        public SafeObservableCollection<MarketplaceApp> Apps { get; set; }
        public MarketplaceUpdater Marketplace = new MarketplaceUpdater();
        public DelegateCommand AppTap { get; private set; }

        private void AppTapImpl(object p)
        {
            try
            {
                var app = p as MarketplaceApp;
                var marketplaceDetailTask = new MarketplaceDetailTask { ContentIdentifier = app.Id };
                marketplaceDetailTask.Show();
            }
            catch { }
        }


        public PublisherAppsControl()
        {
            base.DefaultStyleKey = typeof(PublisherAppsControl);
            //this.Loaded += PublisherAppsControl_Loaded;

            Marketplace.Apps = new List<MarketplaceApp>();
            Apps = new SafeObservableCollection<MarketplaceApp>();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                Marketplace.OSVersion = Environment.OSVersion.Version;
                Marketplace.PublisherName = PublisherName;
                Marketplace.FreeTranslation = LocalizedStrings.FreeLabel;

                this.AppTap = new DelegateCommand(AppTapImpl);
                DataContext = this;
            }
        }

        //void PublisherAppsControl_Loaded(object sender, RoutedEventArgs e)
        //{
        //    var frame = Application.Current.RootVisual as PhoneApplicationFrame;
        //    if (frame == null) return;
        //    var pg = frame.Content as PhoneApplicationPage;
        //    if (pg == null) return;
        //    pg.NavigationService.Navigated += NavigationService_Navigated;
        //}

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            AppsList = GetTemplateChild("AppsList") as ListBox;
            AppsList.SelectionChanged += AppsList_SelectionChanged;
        }

        void AppsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var idx = AppsList.SelectedIndex;
                if (idx == -1) return;
                var app = AppsList.Items[idx] as MarketplaceApp;
                AppsList.SelectedIndex = -1;

                MarketplaceDetailTask t = new MarketplaceDetailTask();
                t.ContentIdentifier = app.Id;
                t.Show();
            }
            catch {}

            //if (idx > 1000 && app == null) throw new Exception();
        }

        /// <summary>
        /// Waiting for layout updated to ensure items materialized
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //void PublisherAppsControl_LayoutUpdated(object sender, EventArgs e)
        //{
        //    if (AppsList != null)
        //    {
        //        foreach (var item in AppsList.Items)
        //        {
        //            DependencyObject dp = AppsList.ItemContainerGenerator.ContainerFromItem(item);
        //            if (dp != null)
        //            {
        //                // -= Removes the event if it has been already added, this prevents multiple firing of the event
        //                (dp as FrameworkElement).Tap -= AppItem_Tap;
        //                (dp as FrameworkElement).Tap += AppItem_Tap;
        //            }
        //        }
        //    }
        //}

        //void NavigationService_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        //{
        //    Reset();
        //}

        //public void Reset()
        //{
        //    navigating = false;
        //}

        #region PublisherName property

        public string PublisherName
        {
            get { return (string)GetValue(PublisherNameProperty); }
            set { SetValue(PublisherNameProperty, value); }
        }

        public static readonly DependencyProperty PublisherNameProperty =
            DependencyProperty.Register("PublisherName", typeof(string), typeof(PublisherAppsControl), new PropertyMetadata(null, PublisherNameChanged));

        private static async void PublisherNameChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var ctrl = (PublisherAppsControl)sender;
            if (ctrl == null || DesignerProperties.GetIsInDesignMode(ctrl)) return;
            try
            {
                ctrl.Marketplace.PublisherName = ctrl.PublisherName;

                VisualStateManager.GoToState(ctrl, "Loading", false);

                if (await ctrl.Marketplace.UpdateMarketplaceApps() == true)
                {
                    ctrl.Apps.Clear();
                    ctrl.Marketplace.Apps.ForEach(a => ctrl.Apps.Add(a));

                    SaveCache(ctrl);
                    VisualStateManager.GoToState(ctrl, "Normal", false);
                }
                else
                {
                    if (ctrl.LoadCache())
                        VisualStateManager.GoToState(ctrl, "Normal", false);
                    else
                        VisualStateManager.GoToState(ctrl, "Error", false);
                }

            }
            catch
            {
                VisualStateManager.GoToState(ctrl, "Error", false);
            }
        }

        #endregion

        #region Cache methods
        private static void SaveCache(PublisherAppsControl ctrl)
        {
            try
            {
                IsolatedStorageSettings.ApplicationSettings["PublisherAppsControls.Items"] = ctrl.Marketplace.Apps;
                IsolatedStorageSettings.ApplicationSettings["PublisherAppsControls.Items.DateTime"] = DateTime.Now;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
            catch { }
        }

        private bool LoadCache()
        {
            try
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("PublisherAppsControls.Items"))
                {
                    var savedApps = (IList<MarketplaceApp>)IsolatedStorageSettings.ApplicationSettings["PublisherAppsControls.Items"];
                    foreach (var a in savedApps) Apps.Add(a);
                }

                if (IsolatedStorageSettings.ApplicationSettings.Contains("PublisherAppsControls.Items.DateTime"))
                    Marketplace.LastUpdate = (DateTime)IsolatedStorageSettings.ApplicationSettings["PublisherAppsControls.Items.DateTime"];

                return true;
            }
            catch { }
            return false;
        }
        #endregion
    }
}

